package aufgabe3_chat;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;

public class Server extends Thread {
	
	//Sleeptime
	private final int SLEEPTIME = 1000;
	
	//Port des Servers
	private int port;
	
	// Soll der Server laufen
	private boolean run_server;
	
	// Logger
	private Logger logger;
	
	// Reffernce auf Master
	private Server_Administration_Control control;
	
	// Reffernce auf Chat_Liste
	private Chat_User_Administration user_list;
	
	/**
	 * Constructor for Server Verwaltet anfragen an einem Port
	 * @param server_a Server_Administration
	 * @param port int Server Port
	 */
	public Server(int port, Server_Administration_Control control,Logger logger) {
		
		user_list = new Chat_User_Administration(logger);
		
		this.port = port;
		this.control = control;
		this.logger = logger;
		run_server = true;
		setDaemon(true);
		
		logger.log("Server", "Server", "Erzeugt");
	}

	@Override
	public void run() {
		logger.log("Server", "Server", "run");
		//Server Socket
		ServerSocket server;
		
		//Server Socket Erstellen
		try {
			server = new ServerSocket(port);
		
			logger.log("Server", "Server","Maintaining");
			while(run_server){
					
				if(control.is_place_for_threads()){
					
					Socket conection = null;
					logger.log("Server", "Server", "Warte auf Connect");
					conection = server.accept();
					control.server_thread_counter_up();
					logger.log("Server", "Server Thread", "Connect");
					new Server_Thread(conection, control,user_list, logger).start();
					logger.log("Server", "Server Thread", "Start");
				} else {
					my_sleep(SLEEPTIME);
				}
			}
		} catch (IOException e1) {
			e1.printStackTrace();
		}
		logger.log("Server", "Server", "Closing");
	}

	private void my_sleep(int time){
		try {
			sleep(time);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
	}
	
	synchronized public void stop_runing() {
		logger.log("Server", "Server",  "Starte Closing");
		run_server = false;
	}
}